import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { userApi } from '@/api/user'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref(null)
  const token = ref(localStorage.getItem('token') || '')
  const isLoading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)
  const userName = computed(() => userInfo.value?.username || '')
  const userAvatar = computed(() => userInfo.value?.avatar || '')

  // 登录
  const login = async (loginForm) => {
    try {
      isLoading.value = true
      const response = await userApi.login(loginForm)
      
      if (response.code === 200) {
        token.value = response.data.token
        userInfo.value = response.data.userInfo
        
        // 保存token到本地存储
        localStorage.setItem('token', token.value)
        
        ElMessage.success('登录成功')
        return true
      } else {
        ElMessage.error(response.message || '登录失败')
        return false
      }
    } catch (error) {
      console.error('登录错误:', error)
      ElMessage.error('登录失败，请检查网络连接')
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 注册
  const register = async (registerForm) => {
    try {
      isLoading.value = true
      const response = await userApi.register(registerForm)
      
      if (response.code === 200) {
        ElMessage.success('注册成功，请登录')
        return true
      } else {
        ElMessage.error(response.message || '注册失败')
        return false
      }
    } catch (error) {
      console.error('注册错误:', error)
      ElMessage.error('注册失败，请检查网络连接')
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await userApi.getProfile()
      if (response.code === 200) {
        userInfo.value = response.data
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，可能token已过期
      logout()
    }
  }

  // 更新用户信息
  const updateProfile = async (profileData) => {
    try {
      isLoading.value = true
      const response = await userApi.updateProfile(profileData)
      
      if (response.code === 200) {
        userInfo.value = { ...userInfo.value, ...profileData }
        ElMessage.success('更新成功')
        return true
      } else {
        ElMessage.error(response.message || '更新失败')
        return false
      }
    } catch (error) {
      console.error('更新用户信息错误:', error)
      ElMessage.error('更新失败，请检查网络连接')
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
    ElMessage.success('已退出登录')
  }

  // 检查登录状态
  const checkLoginStatus = async () => {
    if (token.value) {
      await getUserInfo()
    }
  }

  return {
    // 状态
    userInfo,
    token,
    isLoading,
    
    // 计算属性
    isLoggedIn,
    userName,
    userAvatar,
    
    // 方法
    login,
    register,
    getUserInfo,
    updateProfile,
    logout,
    checkLoginStatus
  }
})